package com.hp.bon.sgw.wh.channel.outside.bizSlotOutQuery.utils;

import com.hp.bon.logreverse.ExtractHelper;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.util.Comutils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Iterator;
import java.util.SortedMap;

/**
 * @PROJECT_NAME: SGW_WH2.1_TMALL
 * @DESCRIPTION:
 * @USER: YouQi
 * @DATE: 2021/5/8 14:35
 */
public class HttpClientUtils {

    private static final Logger _log = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String getHttpStr(String httpUrl) {
        _log.info("===========http url===============" + httpUrl);
        String resp = "";
        _log.info("===========http url===============" + httpUrl);
        GetMethod getMethod = new GetMethod(httpUrl);
        //请求头
        try {
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5 * 1000);
            try {
                client.executeMethod(getMethod);
            } catch (HttpException e) {
                _log.info("===========http call timeout===============" + httpUrl);
                return "";
            } catch (IOException e) {
                _log.info("===========http call timeout session_id:");
                return "";
            }
            try {
                _log.info("===========完成httpUrl===============" + resp);
                InputStream str = getMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(str));
                StringBuffer stringBuffer = new StringBuffer();
                String result = "";
                while((result = br.readLine()) != null) {
                    stringBuffer.append(result);
                }
                resp = stringBuffer.toString();
            } catch (IOException e) {
                _log.info("===========http call timeout===============" + httpUrl);
                return "";
            }
        } catch (Exception e) {
            _log.info("===========http call timeout===============" + httpUrl);
            e.printStackTrace();
            return "";
        }
        return resp;
    }


    public static String postHttpStr(String buildStringMes,String httpUrl) {
        _log.info("===========http url==============="+ httpUrl);
        String resp = "";
        _log.info("===========http url==============="+ httpUrl);
        PostMethod post = new PostMethod(httpUrl);
        //请求头
        try {
            RequestEntity requestEntity = new StringRequestEntity(buildStringMes, "application/json", "UTF-8");
            post.setRequestEntity(requestEntity);
            HttpClient client = new HttpClient();

            client.getHttpConnectionManager().getParams().setConnectionTimeout(5*1000);
            try {
                client.executeMethod(post);
            } catch (HttpException e) {
                _log.info("===========http call timeout==============="+ httpUrl);
                return "";
            } catch (IOException e) {
                _log.info("===========http call timeout session_id:");
                return "";
            }
            try {
                _log.info("===========完成http==============="+resp);
                InputStream str = post.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(str));
                StringBuffer stringBuffer = new StringBuffer();
                String result = "";
                while((result = br.readLine()) != null) {
                    stringBuffer.append(result);
                }
                resp = stringBuffer.toString();
                //resp = post.getResponseBodyAsString();
            } catch (IOException e) {
                _log.info("===========webservice call timeout==============="+ httpUrl);
                return "";
            }
        } catch (UnsupportedEncodingException e) {
            _log.info("===========webservice call timeout==============="+ httpUrl);
            e.printStackTrace();
        }
        return resp;
    }

    public static String directAck(XmlMessage ack, String data)
            throws Exception {
        //String orinData = ack.getDATA();
        String dataStr = "<![CDATA[<Service_Information>" + data + "</Service_Information>]]>";
        String errMsg = ack.getDS();
        errMsg = (errMsg != null) && (errMsg.indexOf('&') == -1) && (errMsg.indexOf('>') == -1) && (errMsg.indexOf('<') == -1) ? errMsg : StringEscapeUtils.escapeXml(errMsg);
        String respXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><ns3:SgwQueryAck xmlns:ns3=\"http://www.chinatelecom.cn/SGW/SOAP\"><MID>" + ack.getMID() + "</MID><REPTAG>0</REPTAG><RTT>" + ack.getRTT() + "</RTT><SIG>" +
                ack.getSIG() + "</SIG><RC>" + ack.getRC() + "</RC><DS>" + errMsg + "</DS><DATA>" + dataStr + "</DATA></ns3:SgwQueryAck></SOAP-ENV:Body></SOAP-ENV:Envelope>";

        if (_log.isInfoEnabled()) {
            _log.info("http response  " + respXML);
        }
        return respXML;
    }

    /**
     * map转xml格式(多结构拼接生成)
     * @param sortedMap
     * @return
     */
    public static String mapToSignXml(SortedMap<Object, Object> sortedMap) throws Exception {
        StringBuilder builder = new StringBuilder();
        Iterator iterator = sortedMap.keySet().iterator();
        while (iterator.hasNext()) {

            Object key = (String) iterator.next();
            Object value = sortedMap.get(key);
            builder.append("<" + key + ">");
            if (value instanceof SortedMap) {
                SortedMap sortedMap1 = (SortedMap) value;
                builder.append(mapToSignXml(sortedMap1));
            } else {
                builder.append(value);
            }
            builder.append("</" + key + ">");

        }
        return builder.toString();
    }

    public static  String  getXmlValue(XmlMessage xmlMes, String keyPath){
        String valueText="";
        try {
            Element dataElement = Comutils.parseText(xmlMes.getDATA()).getRootElement();
            valueText = ExtractHelper.getXmlNodeValue(dataElement, keyPath);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return valueText;
    }



}
